package com.tiantian.novel.rest;

import com.tiantian.novel.service.NovelService;
import io.swagger.annotations.Api;
import org.apache.commons.io.FileUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.OutputStream;
import java.net.URLEncoder;

/**
 * @author wangkai
 * @since 2020/12/23.
 */
@Api("file")
@RequestMapping("/file")
@Controller
public class FileController {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private NovelService novelService;

    /**
     * 下载mobi
     *
     * @param url
     * @return 任务id
     * @throws Exception
     */
    @GetMapping("/mobi/download")
    @ResponseBody
    public void downloadMobi(String url, HttpServletRequest req, HttpServletResponse res) throws Exception {
        log.info("downloadMobi {}", url);
        File mobi = novelService.downloadMobi(url);
        String filename = mobi.getName();
        byte[] buffer = FileUtils.readFileToByteArray(mobi);
        res.reset();
        res.addHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(filename, "utf-8"));
        res.addHeader("Content-Length", "" + buffer.length);
        res.setContentType("application/octet-stream;charset=UTF-8");
        OutputStream out = res.getOutputStream();
        out.write(buffer);
        out.flush();
        out.close();
    }
}
